package org.bb.basic_java_api.common.util;

import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.message.BasicHeader;
import org.elasticsearch.client.Node;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;

public class ClientBuilders {
    private static final String HOSTS = "192.168.61.3:9200,192.168.61.4:9200";

    public static RestClientBuilder getClientBuilder() {
        String[] hostNamesPort = HOSTS.split(",");

        String host;
        int port;
        String[] temp;

        RestClientBuilder restClientBuilder = null;

        /**
         * restClient 初始化
         */
        if (0 != hostNamesPort.length) {
            for (String hostPort : hostNamesPort) {
                temp = hostPort.split(":");
                host = temp[0].trim();
                port = Integer.parseInt(temp[1].trim());
                restClientBuilder = RestClient.builder(new HttpHost(host, port, "http"));
            }
        }

        /**
         * RestClientBuilder 在构建 RestClient 示例时可以设置以下的可选配置参数
         */

        // 1.设置请求头，避免每个请求都必须指定*
        Header[] defaultHeaders = new Header[] {
                new BasicHeader("header", "application/json")
        };
        restClientBuilder.setDefaultHeaders(defaultHeaders);

        // 2.设置在同一请求进行多次尝试时应遵守的超时时间。默认值为30秒，与默认“socket”超时相同。如果自定义了“socket”超时，则应该相应地调整最大重试超时。

        // 3.设置每次节点发生故障时收到通知的侦听器。内部嗅探到故障时被启用
        restClientBuilder.setFailureListener(new RestClient.FailureListener() {
            @Override
            public void onFailure(Node node) {
                super.onFailure(node);
            }
        });

        return restClientBuilder;
    }
}
